<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.cmq.web_1.cart.Product" %>
<%@ page import="com.cmq.web_1.cart.ProductDAO" %>
<html>
<head>
    <title>商品列表</title>
    <style>
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .cart-link { float: right; padding: 8px 15px; background: #0d6efd; color: white; text-decoration: none; border-radius: 5px; }
        .product-list { display: flex; flex-wrap: wrap; gap: 20px; margin-top: 50px; }
        .product-card { width: 250px; padding: 15px; border: 1px solid #ddd; border-radius: 8px; text-align: center; }
        .price { color: #dc3545; font-weight: bold; margin: 10px 0; }
        .add-btn { width: 100%; padding: 8px; background: #28a745; color: white; border: none; border-radius: 3px; cursor: pointer; }
        .message { padding: 10px; background: #d4edda; color: #155724; text-align: center; margin-bottom: 20px; }
    </style>
</head>
<body>
<div class="container">
    <h1>商品列表</h1>

    <%-- 显示提示信息 --%>
    <%
        String message = (String) session.getAttribute("message");
        if (message != null) {
    %>
    <div class="message"><%= message %></div>
    <% session.removeAttribute("message"); } %>

    <%-- 跳转到购物车 --%>
    <a href="${pageContext.request.contextPath}/cart" class="cart-link">查看购物车</a>

    <%-- 商品列表（通过ProductDAO获取，确保不为null） --%>
    <div class="product-list">
        <%
            // 关键修复：通过ProductDAO获取商品，避免直接依赖Servlet
            Map<String, Product> products = ProductDAO.getAllProducts();
            // 即使意外为null，也创建空Map避免报错
            if (products == null) {
                products = new java.util.HashMap<>();
            }
            for (Product p : products.values()) {
        %>
        <div class="product-card">
            <h3><%= p.getName() %></h3>
            <p><%= p.getDescription() %></p>
            <div class="price">¥<%= String.format("%.2f", p.getPrice()) %></div>
            <form action="${pageContext.request.contextPath}/cart" method="post">
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="productId" value="<%= p.getId() %>">
                <button type="submit" class="add-btn">添加到购物车</button>
            </form>
        </div>
        <% } %>
    </div>
</div>
</body>
</html>